<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <style>
            * {
                margin: 0;
                padding: 0;
            }
            img {
                display: block;
                height: 200px;
                outline: solid red;
            }
        </style>
    </head>
    <body>
        <img deta-src="下载.png" src="" />
        <img deta-src="下载.png" src="" />
        <img deta-src="下载.png" src="" />
        <img deta-src="下载.png" src="" />
        <img deta-src="下载.png" src="" />
        <img deta-src="下载.png" src="" />
        <script>
            //定义一个函数，方便进行复用
            function showImg() {
                //获取全部图片元素
                let imgArr = document.querySelectorAll("img");
                //获取滚动条滚动的高度
                let scrollTop =
                    document.body.scrollTop ||
                    document.documentElement.scrollTop;
                //获取浏览器可视窗口的高度
                let clientHeight = document.documentElement.clientHeight;
                ///因为获取的元素是用数组呈现，所以得进行循环遍历取值
                for (let i = 0; i < imgArr.length; ++i) {
                    //获取img元素
                    let img = imgArr[i];
                    //获取图片全部的高度
                    let imgHeight = img.offsetTop;
                    //进行判断什么时候加载，判断公式(scrollTop + clientHeight > imgHeight)
                    //⚠️scrollTop + clientHeight > imgHeight✅记住公式
                    if (scrollTop + clientHeight > imgHeight) {
                        //选取img的deta-src里面的样式
                        let detaSrc = img.getAttribute("deta-src");
                        //更改src的值
                        img.setAttribute("src", detaSrc);
                    }
                }
            }
            showImg();//先渲染一次
            //监测滚动
            window.onscroll = () => {
                showImg();
            };
        </script>
    </body>
</html>
